package com.example.administrator.filetestapplacation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.commons.io.FileUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    private Button bt1, bt2, bt3, bt4, bt5, bt6, bt7;
    private EditText save,write;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1= (Button) findViewById(R.id.save);
        bt2= (Button) findViewById(R.id.write);
        bt3 = (Button) findViewById(R.id.copy);
        bt4 = (Button) findViewById(R.id.copy1);
        bt5 = (Button) findViewById(R.id.copy2);
        bt6 = (Button) findViewById(R.id.copy3);
        bt7 = (Button) findViewById(R.id.copy4);
        save= (EditText) findViewById(R.id.text1);
        write= (EditText) findViewById(R.id.text2);

        //动态申请文件读写权限
        int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//              File sdcard= Environment.getExternalStorageDirectory();
//              File file=new File(sdcard,"1111.text");
                
                File directory = new File("/mnt/sdcard/Test/");
                File file = new File("/mnt/sdcard/Test/test.txt");

//                File directory = new File("/data/data/com.example.administrator.filetestapplacation/cache/");
//                File file = new File("/data/data/com.example.administrator.filetestapplacation/cache/test.txt");

                if(!directory.exists()){
                    directory.mkdir();//没有目录先创建目录  
//                    Toast.makeText(getApplicationContext(), "创建目录成功", Toast.LENGTH_SHORT).show();
                }
                try {
                    if(!file.exists()){
                        file.createNewFile();
                    }
                    FileOutputStream fos=new FileOutputStream(file);
                    OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");//读写文件要保持统一编码方式，否则读取为乱码
                    osw.write(save.getText().toString());
                    osw.flush();
                    osw.close();
                    fos.close();
                    Toast.makeText(MainActivity.this,"保存成功",Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //字节流读写数据
        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File directory = new File("/mnt/sdcard/Test/");
                    File file = new File("/mnt/sdcard/Test/test.txt");

//                    File directory = new File("/data/data/com.example.administrator.filetestapplacation/cache/");
//                    File file = new File("/data/data/com.example.administrator.filetestapplacation/cache/test.txt");
                    if(!directory.exists()){
                        directory.mkdir();
                    }
//                  File sdcard= Environment.getExternalStorageDirectory();
//                  File file=new File(sdcard,"1111.text");
                    FileInputStream fis=new FileInputStream(file);
                    InputStreamReader isr = new InputStreamReader(fis, "utf-8");//读写文件要保持统一编码方式，否则读取为乱码
                    char input[] = new char[fis.available()];//获取fis长度
                    isr.read(input);
                    isr.close();
                    fis.close();
                    write.setText(new String(input));

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //带缓冲的字节流读写数据
        bt3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/Download/3.gif");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/3.gif");//复制文件
                    FileInputStream fis = new FileInputStream(ifile);
                    FileOutputStream fos = new FileOutputStream(wfile);
                    //使用缓存，复制文件效率更高
//                  BufferedInputStream bis=new BufferedInputStream(fis);
//                  BufferedOutputStream bos=new BufferedOutputStream(fos);
                    //添加上缓存大小，应该比byte数组in[]大一些，但也不需要过大，具体适合大小，根据测试消耗时长定
                    BufferedInputStream bis = new BufferedInputStream(fis, 1000);
                    BufferedOutputStream bos = new BufferedOutputStream(fos, 1000);

                    long before = System.currentTimeMillis();

                    //大型文件数组大小可以大一些，小文件对应数组小一些
                    byte in[] = new byte[100];

                    //通过循环，不使用缓存，边读边写
//                    while ((fis.read(in)) > 0) {
//                        fos.write(in);
//                    }
                    while ((bis.read(in)) != -1) {
                        bos.write(in);
                    }
                    bos.close();
                    bis.close();
                    fos.close();
                    fis.close();
                    Log.i("CopyTime", System.currentTimeMillis() - before + "ms");

                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //字符流读写文件
        bt4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/copy.txt");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/copy1.txt");//复制文件

                    FileInputStream fis = new FileInputStream(ifile);
                    FileOutputStream fos = new FileOutputStream(wfile);
                    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
                    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
                    char input[] = new char[100];
                    int l = 0;//主要用来记录最后一次数组长短，写入文件；若不记录，char数组最后一次读取可能不足，将给文件写入多余或错误数据
                    while ((l = isr.read(input)) != -1) {
                        //String inputString = new String(input,0,l);
                        osw.write(input, 0, l);
                    }
                    isr.close();
                    fis.close();
                    osw.close();
                    fos.close();
                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //FileReader、FileWriter直接读写文件，包装缓冲流进行拷贝
        bt5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File ifile = new File("/mnt/sdcard/copy.txt");//目标文件
                    File wfile = new File("/mnt/sdcard/Test/copy2.txt");//复制文件

                    FileReader fr = new FileReader(ifile);
                    BufferedReader br = new BufferedReader(fr);

                    FileWriter fw = new FileWriter(wfile);
                    BufferedWriter bw = new BufferedWriter(fw);

                    String line;
                    while ((line = br.readLine()) != null) {
                        bw.write(line + "\n");
                    }
                    bw.flush();//强制将缓冲流输出

                    bw.close();
                    fw.close();
                    br.close();
                    fr.close();
                    if (wfile.length() > 0) {     //文件大小不为空
                        Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        //RandomAccessFile随机读取,适用多线程下载等操作
        bt6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                File file = new File("/mnt/sdcard/RandomAccessFile随机读取.txt");//目标文件

                //打乱线程順序不影响文件块写入
                new WriteFile(file, 5).start();
                new WriteFile(file, 3).start();
                new WriteFile(file, 1).start();
                new WriteFile(file, 4).start();
                new WriteFile(file, 2).start();

//                    RandomAccessFile raf = new RandomAccessFile(file, "r");//以只读方式打开文件
//                    raf.seek(300);
//                    byte[] str = new byte[20];
//                    raf.read(str);
//                    String in = new String(str);
//                    Log.i("RandomAccessFile随机读取",in);
                Toast.makeText(getApplicationContext(), "文件写入成功", Toast.LENGTH_SHORT).show();
            }
        });
        //通过调用Apache IO的jar包，快捷实现文件的操作
        bt7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    File file1 = new File("/mnt/sdcard/copy.txt");//目标文件
                    File file2 = new File("/mnt/sdcard/Apache IO Copy.txt");//目标文件
//                String input = FileUtils.readFileToString(file1, "UTF-8");//读取文件内容
                    FileUtils.copyFile(file1, file2);
                    Toast.makeText(getApplicationContext(), "文件复制成功", Toast.LENGTH_SHORT).show();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        
    }

}
